package address

import (
	"context"
	"go_final/mxshop_api/userop_web/api"
	"go_final/mxshop_api/userop_web/forms"
	"go_final/mxshop_api/userop_web/global"
	addresspb "go_final/mxshop_api/userop_web/proto/protofile/address"
	"net/http"
	"strconv"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	userID, _ := c.Get("userId")

	res, err := global.AddressClient.GetAddressList(context.Background(), &addresspb.AddressRequest{
		UserID: int32(userID.(uint)),
	})

	if err != nil {
		zap.S().Error("invoke GetAddressList failed", err.Error())
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func Add(c *gin.Context) {
	createAddressForm := forms.CreateAddressForm{}

	err := c.ShouldBind(&createAddressForm)
	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	userID, _ := c.Get("userId")
	res, err := global.AddressClient.CreateAddress(context.Background(), &addresspb.AddressRequest{
		UserID:       int32(userID.(uint)),
		Province:     createAddressForm.Province,
		City:         createAddressForm.City,
		District:     createAddressForm.District,
		Address:      createAddressForm.Address,
		SignerName:   createAddressForm.SignerName,
		SignerMobile: createAddressForm.SignerMobile,
	})
	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"address_id": res.Id,
	})
}

func Delete(c *gin.Context) {
	addressID := c.Param("id")
	addressIDInt, _ := strconv.Atoi(addressID)

	userID, _ := c.Get("userId")

	_, err := global.AddressClient.DeleteAddress(context.Background(), &addresspb.AddressRequest{
		Id:     int32(addressIDInt),
		UserID: int32(userID.(uint)),
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}

func Update(c *gin.Context) {
	updateAddressForm := forms.UpdateAddressForm{}

	err := c.ShouldBind(&updateAddressForm)
	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	addressID := c.Param("id")
	addressIDInt, _ := strconv.Atoi(addressID)

	_, err = global.AddressClient.UpdateAddress(context.Background(), &addresspb.AddressRequest{
		Id:           int32(addressIDInt),
		Province:     updateAddressForm.Province,
		City:         updateAddressForm.City,
		District:     updateAddressForm.District,
		Address:      updateAddressForm.Address,
		SignerName:   updateAddressForm.SignerName,
		SignerMobile: updateAddressForm.SignerMobile,
	})
	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"msg": "更新成功",
	})
}
